<template>
  <div id="user">
    <Loading v-if="total == null"></Loading>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 搜索用户区域 -->
      <el-row :gutter="20">
        <el-col :span="8"
          ><el-input
            placeholder="请输入用户名关键字查询"
            class="input-with-select"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <template #append>
              <el-button icon="el-icon-search" @click="getUserList"></el-button>
            </template> </el-input
        ></el-col>
        <el-col :span="4">
          <el-button type="primary" @click="isShowUserDialog = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userList" border stripe class="mt10">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role.rolename"></el-table-column>
        <el-table-column label="操作" width="180px">
          <template #default="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row._id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row)"
            ></el-button>
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="setRole(scope.row)"
            ></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[1, 5, 10]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>

    <!-- 添加/修改用户对话框 -->
    <el-dialog
      :title="userForm._id ? '修改用户信息' : '添加新用户'"
      v-model="isShowUserDialog"
      width="400px"
      @close="userDialogClose"
    >
      <el-form
        :rules="userFormRules"
        :model="userForm"
        label-width="70px"
        ref="userFormRef"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="userForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShowUserDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveUser">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" v-model="isShowSetRoleDialog" width="400px">
      <div>
        <p>当前用户:{{ userForm.username }}</p>
        <p>
          当前角色:{{
            userForm.role ? userForm.role.rolename : "未分配任何角色"
          }}
        </p>
        <p>
          分配新角色：
          <el-select v-model="userForm.role" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item._id"
              :label="item.rolename"
              :value="item._id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="isShowSetRoleDialog = false">取 消</el-button>
          <el-button type="primary" @click="saveRole">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { reactive, ref, toRefs } from "@vue/reactivity";
import { userFormRules } from "../../data/rules";
import { postData, getData, putData, deleteData } from "../../services/http";
import { getCurrentInstance, onBeforeMount } from "@vue/runtime-core";
export default {
  name: "User",
  setup() {
    const { proxy } = getCurrentInstance();
    const state = reactive({
      userForm: {},
      userList: [],
      roleList: [],
      queryInfo: {
        query: "",
        pageNum: 1,
        pageSize: 5,
      },
      total: null,
    });
    const isShowUserDialog = ref(false);
    const isShowSetRoleDialog = ref(false);
    const stateAsRefs = toRefs(state);
    const userFormRef = ref(null);
    const getUserList = async () => {
      const { data: res } = await getData("rest/users", {
        params: state.queryInfo,
      });
      state.userList = res.data;
      state.total = res.total;
    };
    const getRoleList = async () => {
      const { data: res } = await getData("rest/roles");
      state.roleList = res.data;
    };
    const saveUser = async () => {
      const id = state.userForm._id;
      if (id) {
        await putData(`rest/users/${id}`, state.userForm, "修改成功");
      } else {
        await postData(
          "rest/users",
          state.userForm,
          `已成功添加用户:${state.userForm.username}`
        );
      }
      getUserList();
      isShowUserDialog.value = false;
    };
    const userDialogClose = () => {
      userFormRef.value.resetFields();
    };
    const editUser = async (id) => {
      const res = await getData(`rest/users/${id}`);
      state.userForm = res.data;
      isShowUserDialog.value = true;
    };
    const deleteUser = (row) => {
      const { username, _id } = row;
      proxy
        .$confirm(`此操作将永久删除账户 ${username}, 是否继续?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
        .then(async () => {
          await deleteData(`rest/users/${_id}`, `已成功删除用户 ${username}`);
          getUserList();
        })
        .catch(() => {
          proxy.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    };
    const setRole = (row) => {
      state.userForm = row;
      getRoleList();
      isShowSetRoleDialog.value = true;
    };
    const saveRole = async () => {
      await putData(
        `rest/users/${state.userForm._id}`,
        state.userForm,
        "设置角色成功"
      );
      getUserList();
      isShowSetRoleDialog.value = false;
    };

    const handleCurrentChange = (newPage) => {
      state.queryInfo.pageNum = newPage;
      getUserList();
    };
    const handleSizeChange = (newSize) => {
      state.queryInfo.pageSize = newSize;
      getUserList();
    };
    onBeforeMount(() => {
      getUserList();
      getRoleList();
    });
    return {
      ...stateAsRefs,
      userFormRules,
      userFormRef,
      saveUser,
      deleteUser,
      userDialogClose,
      editUser,
      isShowUserDialog,
      isShowSetRoleDialog,
      setRole,
      saveRole,
      handleCurrentChange,
      handleSizeChange,
      getUserList,
    };
  },
};
</script>

<style>
</style>